//index.js
const app = getApp()
const { $Message } = require('../../dist/base/index');

const setp_rec = {
  DEVICE_PAGE:0,    /** 0设备列表 */
  SERVER_PAGE:1,    /** 1服务列表 */
  CHAR_PAGE:2,      /** 2特征列表 */
  PRO_PAGE:3        /** 3特征属性 */
}

let switchFig = false

let lis_device = []
let lis_server = []
let lis_cha = []
let lis_pro = []

let cho_device_uuid = ""
let cho_server_uuid = ""
let cho_cha_uuid = ""

let now_setp = setp_rec.DEVICE_PAGE

function str2ab(str) {
  var buf = new ArrayBuffer(str.length*2); 
  var bufView = new Uint8Array(buf);
  for (var i=0, strLen=str.length; i<strLen; i++) {
       bufView[i] = str.charCodeAt(i);
  }
  return buf;
}

function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function(bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join(' ');
}

function buf2hex(buffer) { 
  return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join(' ');
}

function Str2Bytes(str)
{
    var pos = 0;
    var reg = new RegExp(" ","g");
    var str2 = str.replace(reg,"");
    var len = str2.length;	
	
    if(len %2 != 0)
       return null; 

    len /= 2;
    var buf = new ArrayBuffer(len);
    var bufView = new Uint8Array(buf);	
    for(var i=0; i<len; i++)
    {
       var s = str2.substr(pos, 2);
       var v = parseInt(s, 16);
       bufView[i] = v;	
       pos += 2;
    }
    return buf;
}

Page({
  data: {
    lis_icon: "enterinto",
    deviceListSwitch: false,
    deviceServerSwitch: false,
    deviceChaSwitch: false,
    openBluetooth_word: "打开蓝牙",
    list_title: "发现设备："
  },

  onLoad: function() {
    this.onBluetoothDeviceFound()
  },
  openBluetooth: function(e){
    console.log("function: openBluetooth")

    if(switchFig == false)
    {
      wx.openBluetoothAdapter({
        success: (res) =>{
          console.log(res)
          wx.startBluetoothDevicesDiscovery({
            success: (res) =>{
              console.log(res)

              wx.showToast({
                title: '打开成功',
              })

              switchFig = true
              this.setData({
                openBluetooth_word: "关闭蓝牙"
              })
              now_setp = now_setp.DEVICE_PAGE
            },
            fail: (err) =>{
              console.log(err)

              wx.showToast({
                title: '打开失败',
              })
            }
          })
        },
        fail: (err) => {
          console.log(err)

          wx.showToast({
            title: '请打开系统蓝牙',
          })
        }
      })
    }
    else
    {
      switchFig = false
      wx.closeBluetoothAdapter()

      lis_device = []
      this.setData({
        list_title: "发现设备：",
        deviceListSwitch: true,
        deviceServerSwitch: false,
        deviceChaSwitch: false,
        deviceProSwitch: false,
        device_list: lis_device,
        lis_icon: "enterinto",
        openBluetooth_word: "打开蓝牙",
        device_list: lis_device
      })
      now_setp = setp_rec.DEVICE_PAGE
    }
  },
  onBluetoothDeviceFound() { 
    wx.onBluetoothDeviceFound(() => { 
      wx.getBluetoothDevices({ 
        success: (res) =>{
          console.log(res)
          lis_device = []
          if(res.devices.length != 0)
          {
            for(var i = 0;i < res.devices.length;i ++)
            {
              if(res.devices[i].name == "未知设备")
                continue

              let mfSw = false
              if(res.devices[i].advertisData)
                mfSw = true

              lis_device.push({
                title:res.devices[i].name,
                label:res.devices[i].deviceId,
                rssi:'信号强度：' + res.devices[i].RSSI + 'dbm',
                _rssi:res.devices[i].RSSI,
                advData:buf2hex(res.devices[i].advertisData),
                ManufacturerDataSwitch:mfSw
              })
            }
            
            lis_device.sort((a,b)=>{
              return b._rssi - a._rssi
            })
            
            console.log(lis_device)
            this.setData({
              deviceListSwitch: true,
              device_list: lis_device
            })
            now_setp = setp_rec.DEVICE_PAGE
          }
          else
          {
            this.setData({
              deviceListSwitch: false
            })
          }
        },
        fail: (err) => {
          console.log(err)
        }
      })
    })
  },
  async createBLEConnection(e){
    console.log("function: createBLEConnection",e.currentTarget.dataset.index)
    console.log("connect device id: ",lis_device[e.currentTarget.dataset.index].label)

    if(switchFig != true)
    {
      wx.showToast({
        title: '请开启蓝牙',
      })
      return
    }

    if(cho_device_uuid != '')
    {
      try{
        let cl =  await wx.closeBLEConnection({
          deviceId: cho_device_uuid,
        })
        console.log(cl)
      }
      catch(e){
        console.log(e)
      }
    }
    
    cho_device_uuid = lis_device[e.currentTarget.dataset.index].label
    wx.createBLEConnection({
      deviceId: cho_device_uuid,
      timeout:6000,
      success: (res) => { 
        console.log(res)
        wx.showToast({
          title: '连接成功',
        })

        this.setData({
          deviceListSwitch: false
        })

        wx.getBLEDeviceServices({ 
          deviceId: cho_device_uuid,
          success: (res) => {
            console.log(res)

            lis_server = []
            for(var i = 0;i < res.services.length;i ++)
            {
              lis_server.push({
                title:res.services[i].uuid,
                label:"server"
              })
            }

            this.setData({
              list_title: "设备服务：",
              deviceServerSwitch: true,
              Server_list: lis_server,
              lis_icon: "undo"
            })
            now_setp = setp_rec.SERVER_PAGE
          }
        })
      },
      fail: (err) => {
        console.log(err)
        wx.showToast({
          title: '连接失败',
        })
      }
    })
    wx.stopBluetoothDevicesDiscovery()
    this.setData({
      showRight1: !this.data.showRight1
  });
  },
  disconnectBLEConnection: function(e){
    console.log("function: disconnectBLEConnection",e)

    lis_cha = []
    this.setData({
      ble_cha_lis: lis_cha,
    })
    
    wx.closeBLEConnection({
      deviceId: cho_device_uuid,
      success: (res) => { 
        console.log(res)
        wx.showToast({
          title: '断开连接',
        })
        this.setData({
          showRight1: !this.data.showRight1
        })
      },
      fail: (err) => {
        console.log(err)
        wx.showToast({
          title: '断开错误',
        })
      }
    })
  },
  deviceServerTouch: function(e){
    console.log("function: deviceServerTouch",e.currentTarget.dataset.index)
    
    cho_server_uuid = lis_server[e.currentTarget.dataset.index].title
    console.log(cho_server_uuid)
    wx.getBLEDeviceCharacteristics({
      deviceId: cho_device_uuid,
      serviceId:cho_server_uuid,
      success: (res) => {
        console.log(res)

        lis_cha = []
        for(var i = 0;i < res.characteristics.length;i ++)
        {
          lis_cha.push({
            title:res.characteristics[i].uuid,
            label:"uuid",
            properties: {
              indicate: res.characteristics[i].properties.indicate,
              notify: res.characteristics[i].properties.notify,
              read: res.characteristics[i].properties.read,
              write: res.characteristics[i].properties.write
            }
          })
        }

        this.setData({
          list_title: "服务特征：",
          deviceServerSwitch: false,
          deviceChaSwitch: true,
          Cha_list: lis_cha                  
        })
        now_setp = setp_rec.CHAR_PAGE
      }
    })
  },
  deviceTitleTouch: function(e){
    console.log("function: deviceTitleTouch")

    switch(now_setp)
    {
      case setp_rec.DEVICE_PAGE:
        console.log("DEVICE_PAGE")
        
        break;
      case setp_rec.SERVER_PAGE:
        console.log("SERVER_PAGE")
                                        console.log(lis_device)
                                        this.setData({
                                          list_title: "发现设备：",
                                          deviceListSwitch: true,
                                          deviceServerSwitch: false,
                                          deviceChaSwitch: false,
                                          deviceProSwitch: false,
                                          device_list: lis_device,
                                          lis_icon: "enterinto"
                                        })
                                        now_setp = setp_rec.DEVICE_PAGE
        break;
      case setp_rec.CHAR_PAGE:
        console.log("CHAR_PAGE")
                                        this.setData({
                                          list_title: "设备服务：",
                                          deviceListSwitch: false,
                                          deviceServerSwitch: true,
                                          deviceChaSwitch: false,
                                          deviceProSwitch: false,
                                          Server_list: lis_server
                                        })
                                        now_setp = setp_rec.SERVER_PAGE
        break;
        case setp_rec.PRO_PAGE:
          console.log("PRO_PAGE")
                                          this.setData({
                                            list_title: "设备特征：",
                                            deviceListSwitch: false,
                                            deviceServerSwitch: false,
                                            deviceChaSwitch: true,
                                            deviceProSwitch: false,
                                            Pro_list: lis_pro            
                                          })
                                          now_setp = setp_rec.CHAR_PAGE
          break;
    }
  },
  deviceChaTouch: function (e) {
    console.log("function: deviceChaTouch",e.currentTarget.dataset.index)
    console.log(lis_cha[e.currentTarget.dataset.index])

    cho_cha_uuid = lis_cha[e.currentTarget.dataset.index].title
    
    lis_pro = []
    lis_pro.push({title:"indicate: " + lis_cha[e.currentTarget.dataset.index].properties.indicate.toString()})

    let bt_sw
    if(lis_cha[e.currentTarget.dataset.index].properties.notify.toString() == "true")
    bt_sw = true
    else
    bt_sw = false

    lis_pro.push({
      title:"notify: " + lis_cha[e.currentTarget.dataset.index].properties.notify.toString(),
      button_sw:bt_sw
    })
    lis_pro.push({title:"read: " + lis_cha[e.currentTarget.dataset.index].properties.read.toString()})

    let in_sw
    if(lis_cha[e.currentTarget.dataset.index].properties.write.toString() == "true")
    in_sw = true
    else
    in_sw = false
    
    lis_pro.push({
      title:"write: " + lis_cha[e.currentTarget.dataset.index].properties.write.toString(),
      input_sw: in_sw,
    })

    this.setData({
      list_title: "特征属性：",
      deviceChaSwitch: false,
      deviceProSwitch: true,
      Pro_list: lis_pro                  
    })
    now_setp = setp_rec.PRO_PAGE
  },
  deviceProTouch: function(e){
    console.log("function: deviceProTouch",e.currentTarget.dataset.index)

  },
  pro_write_cf: function (e) {
    console.log("function: pro_write_cf",e.detail.value)

    console.log(str2ab(e.detail.value))
    
    wx.writeBLECharacteristicValue({
      characteristicId: cho_cha_uuid,
      deviceId: cho_device_uuid,
      serviceId: cho_server_uuid,
      value: Str2Bytes(e.detail.value),
      success:  (res) =>{
        console.log(res)
        wx.showToast({
          title: '写入成功',
        })
      },
      fail: (err) => {
        console.log(err)
        wx.showToast({
          title: '写入失败',
        })
      }
    })
  },
  pro_get_change: function(e){
    console.log(e)

    wx.notifyBLECharacteristicValueChange({
      characteristicId: cho_cha_uuid,
      deviceId: cho_device_uuid,
      serviceId: cho_server_uuid,
      state:true,
      success:  (res) =>{
        console.log(res)
        wx.showToast({
          title: '监听成功',
        })
        
        wx.onBLECharacteristicValueChange(
          (res)=>{
            console.log(res)
            wx.showToast({
              title: '监听到变化',
            })
            console.log(ab2hex(res.value))
            $Message({
              content: ab2hex(res.value),
              duration:10
            });
          }
        )
      },
      fail: (err)=>{
        console.log(err)
        wx.showToast({
          title: '监听失败',
        })
      }
    })
  }
})




